<template>
  <div>
    <!--    面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区-->
    <el-card>
      <!--提示信息-->
      <el-alert
          center
          title="添加商品信息"
          type="info"
          show-icon>
      </el-alert>
      <!--步骤条-->
      <el-steps :active="activeIndex-0" finish-status="success" align-center style="margin: 30px">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--标签页-->
      <el-form :model="addForm" :rules="addRules" ref="Form">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="clickTabs">
          <!--填写基本信息-->
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <br>
              <el-cascader
                  v-model="cateChoose"
                  :options="cateData"
                  :props="{ expandTrigger: 'hover' ,value:'cat_id',label:'cat_name'}"
                  @change="cateChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!--获取动态参数-->
          <el-tab-pane label="商品参数" name="1">
            <!--表格更好看-->
            <el-form>
              <!--循环渲染多选框-->
              <el-form-item v-for="(item,index) in goodDynamicData" style="margin: 20px" :label="item.attr_name">
                <el-checkbox-group v-model="checkListD[index]">
                  <!--把字符串可选性分割成数组-->
                  <el-checkbox border v-for="params in item.attr_vals.split(' ')" :label="params"
                               v-if="params!==''"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
            <!--<el-button @click="text">点我</el-button>-->
          </el-tab-pane>
          <!--获取静态参数-->
          <el-tab-pane label="商品属性" name="2">
            <el-form>
              <!--循环渲染多选框-->
              <el-form-item v-for="(item,index) in goodStaticData" style="margin: 20px" :label="item.attr_name">
                <el-checkbox-group v-model="checkListS[index]">
                  <!--把字符串可选性分割成数组-->
                  <el-checkbox border v-for="params in item.attr_vals.split(' ')" :label="params"
                               v-if="params!==''"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
            <!--<el-button @click="text2">点我</el-button>-->
          </el-tab-pane>
          <!--上传图片-->
          <el-tab-pane label="商品图片" name="3">
            <!--action:图片要上传到的api地址【写完整，这里不是axios，使用没有默认的路径】
                :on-preview  点击图片名称时触发的事件
                :on-remove   点击图片旁边叉号触发的事件
                on-success   图片上传成功的钩子
                list-type   图片呈现样式-->
            <el-upload
                action="https://lianghj.top:8888/api/private/v1/upload"
                :headers="headerObj"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="picSuccess"
                list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>

          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button @click="addGoods" type="primary">添加此商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!--对话框区-->
    <div>
      <!--大图预览对话框-->
      <el-dialog title="图片预览" :visible.sync="isShowBigPic" width="800px">
        <img :src="picSrc" style="width: 100%;">
      </el-dialog>
    </div>
  </div>
</template>

<script>

export default {
  name: "AddGoods",
  data() {
    return {
      //标签页激活的name【步骤条index】
      activeIndex: '0',
      //添加表单的数据
      addForm: {
        goods_name: '',
        goods_cat: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [],
        attrs: [],
      },
      //添加表单的规则
      addRules: {
        goods_name: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
        goods_cat: [{required: true, message: '请输入商品类型', trigger: 'blur'}],
        goods_price: [{required: true, message: '请输入商品价格', trigger: 'blur'}],
        goods_number: [{required: true, message: '请输入商品数量', trigger: 'blur'}],
        goods_weight: [{required: true, message: '请输入商品重量', trigger: 'blur'}],
        goods_introduce: [{required: true, message: '请输入商品介绍', trigger: 'blur'}],
        pics: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
        attrs: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
      },
      //商品分类参数
      cateData: [],
      //选择的商品的类别
      cateChoose: [],
      //商品静态参数获取
      goodStaticData: [],
      //商品动态参数获取
      goodDynamicData: [],
      checkListS: [],
      checkListD: [],
      //图片上传的请求头设置
      headerObj: {Authorization: window.sessionStorage.getItem('token')},
      //大图预览显示
      isShowBigPic: false,
      // 当前图片路径
      picSrc: ''
    }
  },
  methods: {
    //级联选择器发生数据变化，获取动态静态参数
    cateChange() {
      if (this.cateChoose.length !== 3) return this.cateChoose = []
      this.addForm.goods_cat = this.cateChoose.join(',')
      //获取静态参数
      this.$http.get(`categories/${this.cateChoose[2]}/attributes`, {params: {sel: 'only'}}).then(res => {
        // console.log("静态")
        // console.log(res)
        this.goodStaticData = res.data.data
        for (let i = 0; i < this.goodStaticData.length; i++) {
          this.checkListS[i] = []
        }
      })
      //获取动态参数
      this.$http.get(`categories/${this.cateChoose[2]}/attributes`, {params: {sel: 'many'}}).then(res => {
        // console.log("动态")
        // console.log(res)
        this.goodDynamicData = res.data.data
        for (let i = 0; i < this.goodDynamicData.length; i++) {
          this.checkListD[i] = []
        }
      })
    },
    //添加商品
    addGoods() {
      //将商品的参数赋值给addForm
      for (let i = 0; i < this.checkListD.length; i++) {
        this.addForm.attrs.push({
          attr_id: this.goodDynamicData[i].attr_id,
          attr_value: this.checkListD[i].join(' ')
        })
      }
      for (let i = 0; i < this.checkListS.length; i++) {
        this.addForm.attrs.push({
          attr_id: this.goodStaticData[i].attr_id,
          attr_value: this.checkListS[i].join(' ')
        })
      }
      this.$http.post('goods', this.addForm).then(res => {
        if (res.data.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('添加商品成功')
        this.$router.push('/home/goods')  //跳转商品列表
      })
      console.log("添加的商品")
      console.log(this.addForm)
    },
    //点击标签页的切换
    clickTabs() {
      if (this.cateChoose.length !== 3) {
        this.$message.error('请先选择商品类别')
        return false
      }
    },
    //点击图片名称预览
    handlePreview(file) {
      console.log(file)
      this.isShowBigPic = !this.isShowBigPic
      this.picSrc=file.response.data.url
    },
    //点击叉号
    handleRemove(file, fileList) {
      // file里面有临时路径，可以通过这个找到pic里对应的
      const filePath = file.response.data.tmp_path
      //findIndex(n=>{})：数组查找：里面是一个回调函数，n表示从索引0开始查找的每一项，然后如果里面的结果返回为真，则返回找到第一个为真的索引
      const i = this.addForm.pics.findIndex(n => n.pic === filePath)
      //splice(x,y,z):数组删除替换：x开始的索引，y替换几个，z替换进来的值
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm.pics)
    },
    //图片上传成功
    picSuccess(res, file, fileList) {
      //将图片对象储存到我们的数据中
      this.addForm.pics[0] = {
        pic: res.data.tmp_path
      }
    }
    // text(){
    //   console.log(this.checkListD)
    //   for(let i = 0; i < this.checkListD.length; i++){
    //     this.addForm.attrs.push({
    //           attr_id:this.goodDynamicData[i].attr_id,
    //           attr_value:this.checkListD[i].join(' ')
    //     })
    //   }
    //   // for (let i = 0; i < this.checkListD.length; i++) {
    //   //   this.addForm.attrs[i]={
    //   //     attr_id:this.goodDynamicData[i].attr_id,
    //   //     attr_value:this.checkListD[i].join(' ')
    //   //   }
    //   // }
    //   console.log(" this.addForm.attrs")
    //   console.log( this.addForm.attrs)
    // },
    // text2(){
    //   console.log(this.checkListS)
    //   for (let i = this.checkListD.length; i < this.checkListD.length+this.checkListS.length; i++) {
    //     this.addForm.attrs[i]={
    //       attr_id:this.goodStaticData[i-this.checkListD.length].attr_id,
    //       attr_value:this.checkListS[i-this.checkListD.length].join(' ')
    //     }
    //   }
    // console.log(" this.addForm.attrs")
    // console.log( this.addForm.attrs)
    // },
  },


  created() {
    this.$http.get('categories').then(res => {
      this.cateData = res.data.data
      console.log(res)
    })
  }
}
</script>

<style scoped>
.el-button{
  margin-top: 20px;
}
</style>